<template>
<div>
    <page-header-wrapper></page-header-wrapper>
    <a-card style="margin-top: 20px">
        <div class="table-page-search-wrapper">
            <a-form :form="searchForm" layout="inline">
                <a-row :gutter="48">
                    <SearchFormItems  :md="{span:8}" :sm="{span:24}" :searchKeys="OrderListSearchKeys" :advanceVal="advanced" :getDataWithKey="getDataWithKey">
                    </SearchFormItems>
                    <a-col :md="(!advanced && 8) || 6" :sm="6" class="advanced_butns">
                        <span class="table-page-search-submitButtons" :style="
                            (advanced && { float: 'right', overflow: 'hidden' }) || {}
                        ">
                            <a-button @click="reset">重置</a-button>
                            <a-button type="primary" @click="search">查询</a-button>
                            <a @click="toggleAdvanced">
                                {{ advanced ? '收起' : '展开' }}
                                <a-icon :type="advanced ? 'up' : 'down'" />
                            </a>
                        </span>
                    </a-col>
                </a-row>
            </a-form>
            
        </div>
        <a-tabs v-model="currOrderTab" @change="tabChange">
            <a-tab-pane key="-1" tab="全部"></a-tab-pane>
            <a-tab-pane v-for="item in tabLists" :key="''+item.key" :tab="item.value" />
        </a-tabs>
    </a-card>
    <div class="cont_box">
        <div class="table_header flex-between">
            <div class="table_name">{{pageTitle}}</div>
            <div class="table_butns flex-end">
                <a-button v-if="currOrderTab == 2" size="default" type="default" :disabled="selectedRowKeys.length == 0" @click="batchPay">
                    批量支付
                </a-button>
                <a-button size="default" type="default" :loading="unmatchLoading"  @click="downloadUnmatch">
                    导出未匹配商品
                </a-button>
                <!-- <a-button size="default" type="link" @click="downloadExample">
                    Excel模板
                </a-button> -->
                <a-button size="default" type="default" :disabled="selectedRowKeys.length == 0" @click="batchCancel">
                    批量作废
                </a-button>
            </div>
        </div>
        <a-table :columns="OrderListColumn" 
            :dataSource="dataSource" 
            :pagination="pagination" 
            :rowKey="(it) => it.id " 
            :rowSelection="{
                selectedRowKeys: selectedRowKeys,
                onChange: onSelectChange
            }" 
            :loading="loading" binvested :scroll="{ x: 1500 }">
            <a-popover slot="orderNo" slot-scope="record">
                <template slot="content">
                    <p>{{ record.orderNo }}</p>
                </template>
                <p class="txt-over-2 two_line flex-center" style="color:#1890ff;margin:0;height: 49px;">{{ record.orderNo }}</p>
            </a-popover>
            <a slot="designUrl" slot-scope="record">{{ record.designUrl }}</a>
            <a slot="effectUrl" slot-scope="record">{{ record.effectUrl }}</a>
            <a-badge slot="status" slot-scope="text" :status="text.status == 1 ?'success':'error'" :text="getStatusName(text.status)" />
            <span slot="operation" slot-scope="text, record">
                <template v-if="record.status == '未匹配' || record.status == '已取消'|| record.status == '待支付'">
                    <a-button size="small" type="link" @click="showModal(record)">
                        编辑
                    </a-button>
                    <a-button size="small" type="link" @click="cancelOrder(record)">
                        作废
                    </a-button>
                </template>
                <a-button size="small" type="link" @click="goDetail(record)">
                    详情
                </a-button>
                <a-button size="small" type="link" @click="checkMerge(record)">
                    查看合并
                </a-button>
            </span>
        </a-table>
        <pagination :total="total" :page.sync="page" :size.sync="size" :onPageSizeChange="onPageSizeChange" :onShowSizeChange="onShowSizeChange" />
        <a-modal title="编辑" v-model="editVisible" destroyOnClose @ok="sureModal" width="600px">
            <div class="modal_body_cont">
                <a-form :form="modalForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                    <modalFormItem :searchKeys="listModalKeys" :getDataWithKey="getDataWithKey"></modalFormItem>
                </a-form>
            </div>
        </a-modal>
    </div>
</div>
</template>

<script>
import {
    OrderListSearchKeys,
    OrderListColumn,
    listModalKeys
} from './config'
import {orderStatusList,
    orderEnum,
    getOrderList,
    orderCancel,
    orderUpdate,
    orderTemplate,
    exportUnmatchGoods
} from '@/api/order'
import {billCreate,billPay,billQuery} from '@/api/pay.js'

export default {
    name: 'OrderList',
    data() {
        return {
            currOrderTab:'',
            tabLists: [],
            pageTitle:'',
            OrderListSearchKeys,
            OrderListColumn,
            // 高级搜索 展开/关闭
            advanced: false,
            // 查询参数
            queryParam: {},
            dataSource: [],
            pagination: false,
            page: 1,
            size: 50,
            total: 0,
            loading: false,
            selectedRowKeys: [],
            selectedRows: [],
            editVisible: false,
            searchForm:this.$form.createForm(this, { name:'order_list_search' }),
            modalForm: this.$form.createForm(this, {
                name: "order_list_modal"
            }),
            listModalKeys,
            statusArrs: [],
            orderId:'',
            unmatchLoading:false
        }
    },
    computed: {
        getDataWithKey() {
            return key => {
                switch (key) {
                    case "status":
                        return this.statusArrs
                    default:
                        return [];
                }
            };
        },
    },
    created() {
        this.pageTitle = this.$route?.meta?.title
        this.getOrderCategory()
        this.getOrderStatus()
        this.getList();
    },
    methods: {
        async getOrderCategory(){
            let res = await orderStatusList()
            this.currOrderTab = '-1'
            this.tabLists = res?.data
        },
        tabChange() {
            this.page = 1;
            this.getList();
        },
        search() {
            this.page = 1;
            this.getList();
        },
        reset() {
            this.searchForm.resetFields();
            this.page = 1;
            this.getList();
        },
        async getOrderStatus() {
            let status = await orderEnum()
            this.statusArrs = status?.data
        },
        getStatusName(status){
            let tem = this.statusArrs.filter(item =>{return item.key == status}); 
            if(tem && tem.length>0){
                return tem[0]?.value
            }else{
                return ''
            }
        },
        onPageSizeChange(page, size) {
            this.selectedRowKeys = []
            this.page = page;
            this.getList(page, size);
        },
        onShowSizeChange(page, size){
            console.log(page, size)
            this.selectedRowKeys = []
            this.page = page;
            this.size = size;
            this.getList(page, size);
        },
        cancelOrder(record){
            this.$confirm({
                title: `确定要作废吗？`,
                content: '',
                okText: '作废',
                okType: 'danger',
                cancelText: '取消',
                onOk: () => {
                    orderCancel({ids:[record.id]}).then(res =>{
                        this.$message.success('操作成功')
                        this.getList()
                    })
                },
            })
        },
        goDetail({sysOrderNo}){
            this.$router.push({
                name:'OrderDetail',
                query:{
                    id:sysOrderNo
                }
            })
        },
        checkMerge(){
            this.$router.push({
                name:'OrderMerge',
            })
        },
        batchCancel(){
            console.log(this.selectedRowKeys)
            orderCancel({ids:this.selectedRowKeys}).then(res =>{
                this.$message.success('操作成功')
                this.selectedRowKeys = []
                this.getList()
            })
        },
        async batchPay(){
            let selectIds = this.selectedRowKeys,selectOrs = this.dataSource,temOrderIds = []
            for(let i=0;i<selectIds.length;i++){
                let temArr = selectOrs.filter(item => {return item.id == selectIds[i]})
                temOrderIds.push(temArr[0]?.sysOrderNo)
            }
            console.log(this.selectedRowKeys,temOrderIds)
            let createRes = await billCreate({sysOrderNoList:temOrderIds})
            if(createRes?.success){
                this.$message.success('支付订单创建成功')
                setTimeout(()=>{
                    let {paymentBatchId = '',actualAmount=0} = createRes?.data, 
                        createObjs = {paymentBatchId,amount:actualAmount,payType:'balance',payChannel:'0'}
                    this.billPay(createObjs)
                },2000)
                
            }else{
                this.$message.error(createRes?.message)
            }
        },
        async billPay(obj){
            let res = await billPay(obj)
            if(res?.success){
                let queryRes = await billQuery(obj.paymentBatchId)
                if(queryRes?.data?.pay){
                    this.$message.success('支付成功')
                }else{
                    this.$message.error('支付失败')
                }
                this.selectedRowKeys = []
                this.getList()
            }else{
                this.$message.error(res?.message)
                this.selectedRowKeys = []
                this.getList()
            }

            
        },
        // 获取列表
        async getList(currentPage, currentSize) {
            this.loading = true
            const { page, size, currOrderTab } = this;
            let queryParam = this.searchForm.getFieldsValue(),orderNos = []
            if(queryParam && queryParam.orderNos){
                if(queryParam.orderNos.indexOf('\n')>-1){
                orderNos = queryParam.orderNos.split('\n')
                }else{
                orderNos.push(queryParam.orderNos)
                }
            }
            this.searchForm.validateFields(async (err, values) => {
                if (!err) {
                    let params = {
                        pageNum: (currentPage) || (page),
                        pageSize: currentSize || size,
                        ...values,
                        orderNos
                        // orders: [{
                        //     column: 'id',
                        //     asc: false,
                        // }]
                    };
                    if(currOrderTab != '-1'){
                        params.orderStatus = currOrderTab
                    }
                    const res = await getOrderList(params)
                    this.total = res?.data?.total || 0;
                    this.dataSource = res?.data?.list || []
                    this.loading = false
                } else{
                    this.loading = false
                }
            })
        },
        downloadExample(){
            orderTemplate().then(res =>{
                window.open(res?.data);
            })
        },
        async downloadUnmatch(){
            this.unmatchLoading = true
            let res = await exportUnmatchGoods()
            const link = document.createElement("a"); // 创建a标签
            let blob = new Blob([res], {
            type: "application/vnd.ms-excel;charset=UTF-8",
            }); // 设置文件类型
            link.style.display = "none";
            link.href = URL.createObjectURL(blob); // 将文件流转化为blob地址
            link.setAttribute("download",'未匹配商品.xlsx');//文件名，而不是写死.excel之类
            document.body.appendChild(link);//创建
            link.click();//点击事件
            document.body.removeChild(link);
            this.unmatchLoading = false
        },
        showModal(record) {
            this.editVisible = true
            if(record){
                let {id,orderNo,userName,skuName,qty,price,freight,designUrl, effectUrl,addr1,addr2,email,extend1,extend2,extend3,status} = record
                    this.orderId = id
                    this.$nextTick(() => {
                    setTimeout(() => {
                        this.modalForm.setFieldsValue({orderNo,userName,skuName,qty,price,freight,designUrl, effectUrl,addr1,addr2,email,extend1,extend2,extend3,status})
                    },400)
                });
            }else{
                this.orderId = ''
                this.modalForm.resetFields()
            }
        },
        sureModal() {
            let {orderId} = this
                this.modalForm.validateFields(async (err,values) => {
                    if(!err){
                        let params = {
                            ...values,
                            id:orderId,
                        }
                        orderUpdate(params).then(res =>{
                            this.$message.success('编辑成功')
                            this.orderId = ''
                            this.editVisible = false
                            this.getList()
                        })
                    }
                })
        },
        onSelectChange(selectedRowKeys, selectedRows) {
            this.selectedRowKeys = selectedRowKeys;
            this.selectedRows = selectedRows;
        },
        toggleAdvanced() {
            this.advanced = !this.advanced;
        },
    },
};
</script>
